﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UtilsORM;
using UtilsORM.MySqlData;

namespace ServiceWeb.DBGateway
{
    public class DBIotProductModel
    {

        EFYihongIotContext ef = new EFYihongIotContext();

        private static object obj = new object();
        public bool saveAll(MagerLoginInfo LoginUserInfo, iot_product_model reqModel)
        {
            lock (obj)
            {

                //先查一下有没重复提交
                iot_product_model model = ef.iot_product_model.Where(c => c.pm_guid == reqModel.pm_guid).FirstOrDefault();
                if (model == null)
                {
                    //查编码
                    iot_product_model getcode = ef.iot_product_model.OrderByDescending(c => c.pm_id).FirstOrDefault();
                    if (getcode != null)
                    {
                        string pm_code = getcode.pm_code.Replace("pm", "");
                        reqModel.pm_code = "pm" + (int.Parse(pm_code) + 1).ToString();
                    }
                    else
                    {
                        reqModel.pm_code = "pm1001";
                    }
                    //写入
                    reqModel.pm_status = 0;
                    reqModel.pm_add_time = DateTime.Now;
                    reqModel.pm_c_guid = LoginUserInfo.userCompanyGuid;
                    reqModel.pm_p_guid = reqModel.pm_p_guid;
                    ef.iot_product_model.Add(reqModel);
                    ef.SaveChanges();

                    //更新
                    iot_product product = ef.iot_product.Where(c => c.p_guid == reqModel.pm_p_guid).FirstOrDefault();
                    product.p_pm_guid = reqModel.pm_guid;
                    ef.iot_product.Update(product);
                    ef.SaveChanges();

                }
                else
                {
                    model.pm_name = reqModel.pm_name;
                    model.pm_remark = reqModel.pm_remark;
                    model.pm_add_time = DateTime.Now;
                    model.pm_status = reqModel.pm_status;
                    ef.iot_product_model.Update(model);
                    ef.SaveChanges();

                }
            }
            return true;

        }
    }
}
